package com.lzh.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @ClassName RabbitMQConfig
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/9/7 17:58
 * @Version 1.0
 **/
@Configuration
public class RabbitMQConfig {
    /**
     * 使用json序列化机制，进行消息转换
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 库存微服务的交换机
     * @return
     */
    @Bean
        public Exchange stockEventExchange(){
            return new TopicExchange("stock-event-exchange",true,false);
    }

    /**
     * 普通队列
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue("stock.release.stock.queue",true,false,false,null);
    }
    /**
     * 死信队列(延迟队列)
     * @return
     */
    @Bean
    public Queue stockDelayQueue(){
       /*
            Queue(String name,  队列名字
            boolean durable,  是否持久化
            boolean exclusive,  是否排他
            boolean autoDelete, 是否自动删除
            Map<String, Object> arguments) 属性
         */
        HashMap<String, Object> arguments = new HashMap<>();
        //死信路由
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        //路由键
        arguments.put("x-dead-letter-routing-key", "stock.release");
        //消息过期时间1分钟，毫秒为单位
        arguments.put("x-message-ttl", 60000);
        Queue queue = new Queue("stock.delay.queue", true, false, false, arguments);
        return queue;
    }

    /**
     * 交换机和普通队列的绑定关系
     * @return
     */
    @Bean
    public Binding stockReleaseBinding() {
        /*
         * String destination, 目的地（队列名或者交换机名字）
         * DestinationType destinationType, 目的地类型（Queue、Exhcange）
         * String exchange,
         * String routingKey,
         * Map<String, Object> arguments
         * */
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }

    /**
     * 交换机与延迟队列绑定
     * @return
     */
    @Bean
    public Binding stockLockedBinding() {
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }

    /**
     *第一次连上rabbitmq,没有的组件才会去创建
     * @param message
     */
//     @RabbitListener(queues = "stock.release.stock.queue")
     public void handle(Message message) {

     }
}
